import { Component, OnInit } from '@angular/core';
import {CartResult} from '../../../shared/cartResult.interface';
import {Cart1Service} from '../../../service/cart.service';
import {AuthService} from '../../../auth/auth.service';


@Component({
  selector: 'app-mini-cart',
  templateUrl: './mini-cart.component.html',
  styleUrls: ['./mini-cart.component.less']
})
export class MiniCartComponent implements OnInit {
  subscription;
  logined;
  cartResult: CartResult = {
    cart: [],
    totalNumber: 0,
    totalPrice: 0,
    selectedTotalNumber: 0,
    selectedTotalPrice: 0,
    allS: true,
  };
  product = {
    goodsId: 0,
    productIsSelected: false,
    userName: '',
    id: '',
    quantity: 0
  };
  constructor(
    private cartService: Cart1Service,
    private authService: AuthService
  ) { }

  ngOnInit() {
    this.cartResult = this.cartService.result;
  }
  // 如果登录，把本地购物车添加到线上购物车,并获取线上购物车数据
  addToOnlineCart() {
    const localC = localStorage.getItem('cart');
    const localCart = JSON.parse(localC);
    if (localCart && localCart.cart && localCart.cart.length) {
      for (const c of localCart.cart) {
        this.product.goodsId = c.goodsId;
        this.product.productIsSelected = c.productIsSelected;
        this.product.quantity = c.quantity;
        this.product.userName = this.logined.data.userName;
        this.product.id = this.logined.data.userName + '_' + c.goodsId;
        this.cartService.addToCart(this.product)
          .subscribe(
            (response) => {
              if (response.code === 1) {
                this.getCarts();
              }
            }
          );
      }
      localStorage.removeItem('cart');
    }
    this.getCarts();
  }
  // 获取线上购物车数据
  getCarts() {
    this.cartService.getCartList().subscribe(
      (products) => {
        this.cartResult = products;
        this.cartResult.cart = products.cart;
      }
    );
  }
  // 获取本地购物车数据
  getLocalCarts() {
    this.cartResult = this.cartService.localGetCart();
    this.subscription = this.cartService.cartChanged.subscribe(
      (products: CartResult) => {
        this.cartResult = products;
      }
    );
  }
  onDelete(id: number) {
    if (this.logined) {
      this.cartService.deleteProduct(id)
        .subscribe(
          (result) => {
            if (result.code === 1) {
              this.getCarts();
            }
          }
        );
    } else {
      this.cartService.localDeleteProduct(id);
    }
  }
}
